<template>
    <div class="subject-form">
        <el-form ref="subjectForm" :model="subjectData" label-width="120px" :rules="rules">
            <!-- 题目标题 -->
            <el-form-item label="题目标题" prop="subjectTitle">
                <el-input v-model="subjectData.subjectTitle" placeholder="请输入题目标题"></el-input>
            </el-form-item>

            <!-- 题目详情 -->
            <el-form-item label="题目详情" prop="detailDescription">
                <el-input v-model="subjectData.detailDescription" type="textarea" :rows="4"
                    placeholder="请输入题目详情"></el-input>
            </el-form-item>

            <!-- 题目难度 -->
            <el-form-item label="题目难度" prop="difficult">
                <el-select v-model="subjectData.difficult" placeholder="请选择题目难度">
                    <el-option label="简单" :value="1"></el-option>
                    <el-option label="中等" :value="2"></el-option>
                    <el-option label="困难" :value="3"></el-option>
                </el-select>
            </el-form-item>

            <!-- 测试用例文件 JSON -->
            <el-form-item label="测试用例文件 JSON" prop="testCase">
                <el-input v-model="subjectData.testCase" type="textarea" :rows="4"
                    placeholder="请输入测试用例文件 JSON 数据"></el-input>
            </el-form-item>

            <!-- 题目提示 -->
            <el-form-item label="题目提示" prop="subjectTip">
                <el-input v-model="subjectData.subjectTip" type="textarea" :rows="4"
                    placeholder="请输入题目提示（JSON数组格式）"></el-input>
            </el-form-item>

            <!-- 用户代码模板 -->
            <el-form-item label="用户代码模板" prop="codeTemplate">
                <el-input v-model="subjectData.userCodeTemplate" type="textarea" :rows="4" placeholder="请输入代码模板"></el-input>
            </el-form-item>

            <!-- 运行时代码模板 -->
            <el-form-item label="运行时代码模板" prop="codeTemplate">
                <el-input v-model="subjectData.runtimeCodeTemplate" type="textarea" :rows="4" placeholder="请输入代码模板"></el-input>
            </el-form-item>

            <!-- 标签 ID 列表 -->
            <el-form-item label="标签 ID 列表" prop="labelIdList">
                <el-select v-model="subjectData.labelIdList" multiple placeholder="请选择标签">
                    <el-option :label="item.labelTitle" :value="item.id" v-for="item in labelList"></el-option>
                </el-select>
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { ElMessage, type ElForm } from 'element-plus';
import type { ojLable } from '@/typedefined/Label';
import { subjectApi, tagApi } from '@/request';
import { BusinessException } from '@/exception/BusinessException';
import type { SubjectAddDTO } from '@/typedefined/DTO';

// 标签列表
const labelList = ref<Array<ojLable>>([]);

// 组件挂载完毕执行的钩子函数
onMounted(async () => {
    try {
        // 请求标签列表
        const dataLabelList = await tagApi.getojTag() as unknown as Array<ojLable>;
        // 切换数据源
        labelList.value = dataLabelList;
    } catch (e) {
        throw new BusinessException("请求标签列表失败");
    }
});

// 表单数据
const subjectData = ref<SubjectAddDTO>({
    subjectTitle: '',
    detailDescription: '',
    difficult: null,
    testCase: '', // 默认为空字符串
    subjectTip: '',
    userCodeTemplate: '',
    labelIdList: [],
    runtimeCodeTemplate:''
});

// 表单引用
const subjectForm = ref<InstanceType<typeof ElForm> | null>(null);

// 自定义验证函数：验证 JSON 格式
const validateTestCase = (rule: any, value: string, callback: any) => {
    try {
        JSON.parse(value);
        callback();
    } catch (error) {
        callback(new Error('请输入有效的 JSON 格式'));
    }
};

// 表单验证规则
const rules = {
    subjectTitle: [
        { required: true, message: '题目标题不能为空', trigger: 'blur' },
    ],
    detailDescription: [
        { required: true, message: '题目详情不能为空', trigger: 'blur' },
    ],
    difficult: [
        { required: true, message: '题目难度不能为空', trigger: 'change' },
    ],
    testCase: [
        { required: true, message: '测试用例文件 JSON 不能为空', trigger: 'blur' },
        { validator: validateTestCase, trigger: 'blur' },
    ],
    subjectTip: [
        { required: true, message: '题目提示不能为空', trigger: 'blur' },
    ],
    userCodeTemplate: [
        { required: true, message: '代码模板不能为空', trigger: 'blur' },
    ],
    runtimeCodeTemplate: [
        { required: true, message: '代码模板不能为空', trigger: 'blur' },
    ],
    labelIdList: [
        { required: true, message: '至少选择一个标签', trigger: 'change' },
    ],
};


// 提交表单
const submitForm = () => {
    subjectForm.value?.validate(async (valid) => {
        if (!valid) return alert("检查表单是否完整");
        const success = await subjectApi.oj.addSubject(subjectData.value) as unknown as boolean;
        if(!success){
            throw new BusinessException("新增题目失败");
        }
        ElMessage({type:"success",message:"新增成功"});
        resetForm(); // 重置表单内容
    });
};

// 重置表单
const resetForm = () => {
    subjectForm.value?.resetFields();
};
</script>

<style scoped>
.subject-form {
    max-width: 600px;
    margin: 20px auto;
}
</style>